<?php

require_once ROOT_DIR.'models/User.php';
require_once ROOT_DIR.'models/TodoList.php';

/**
 * @author Immanuel Bauer | 0626117
 */
class TodoJSON {
	
	/**
	 * Generates the JSON view for the given Todo model object or an array of Todo model objects.
	 * @param Todo/array $todo
	 * @param int $todoCount
	 * @return string
	 */
	public static function getView($todo, $todoCount = null, $linkedLists = false){
		$field = 'todo';
		if(is_array($todo)){
			$field = 'todos';
			$a = array();
			$tc = count($todo);
			for($c = 0; $c < $tc; $c++){
				$t = $todo[$c];
				$ta = array(
					'id' => $t->getID(),
					'title' => $t->getTitle(),
					'text' => $t->getDescription(),
					'tD' => $t->getTargetDate(),
					'pH' => $t->getProjectedHours(),
					'status' => $t->getStatus(),
					'creator' => $t->getCreatorID()
				);
				if($linkedLists) $ta['lists'] = TodoJSON::buildLinkedListArray($t);
				array_push($a, $ta);
			}
		} else {
			$a = array(
					'id' => $todo->getID(),
					'title' => $todo->getTitle(),
					'text' => $todo->getDescription(),
					'tD' => $todo->getTargetDate(),
					'pH' => $todo->getProjectedHours(),
					'status' => $todo->getStatus(),
					'creator' => $todo->getCreatorID(),
					'users' => TodoJSON::buildUserArray($todo)
				);
			if($linkedLists) $a['lists'] = TodoJSON::buildLinkedListArray($todo);
		}		
		
		$res = new ResultJSON(false, session_id());
		$res->addItem($field, $a);
		if(!is_null($todoCount)) $res->addItem('tC', $todoCount);
		
		return $res->renderView();
	}
	
	/**
	 * Builds the array of users linked to the todo
	 * @param Todo $todo
	 * 
	 * @return array
	 */
	private function buildUserArray($todo){
		$users = User::getUsersLinkedToTodo($todo->getID());
		$uc = count($users['users']);
		$a = array();
		
		for($c = 0; $c < $uc; $c++){
			$user = $users['users'][$c];
			$u = array(
					'id' => $user->getID(),
					'nick' => $user->getLoginName(),
					'fN' => $user->getFirstName(),
					'lN' => $user->getLastName(),
					'role' => $users['roles'][$c]);
			array_push($a, $u);
		}
		
		return $a;
	}
	
	/**
	 * Builds the array of lists linked to the todo
	 * @param Todo $todo
	 * 
	 * @return array
	 */
	private function buildLinkedListArray($todo){
		$lists = TodoList::getListsLinkedWithTodo($todo->getID());
		$lc = count($lists);
		$a = array();
		
		for($c = 0; $c < $lc; $c++){
			$list = $lists[$c];
			$l = array(
					'id' => $list->getID(),
					'title' => $list->getName()
			);
			array_push($a, $l);
		}
		
		return $a;
	}
	
}

?>